import React from "react"
import {
  Icon,
  Divider,
  Affix,
  Button,
  Card,
  Row,
  Col,
  Timeline,
  Collapse,
  Badge,
  Spin,
  Tooltip,
  Modal,
  message,
  Checkbox,
  Popconfirm
} from 'antd'
import {messages} from "share/common";
import constants from 'share/constants'
import customField from 'share/customField'
import menuRoute from 'routes/menuRoute'
import SlideFrame from 'components/slide-frame'
import bookingManagerService from 'containers/booking-management/booking-manager.service'
import 'styles/booking-management/booking-details.scss'
import moment from "moment/moment";
import BookingDetailsMaintain from "containers/booking-management/booking-details-maintain";
import ResizeTable from 'components/resize-table'

const Panel = Collapse.Panel;
const CheckboxGroup = Checkbox.Group;

import TicketInfo from './ticket-info';
import BookingUtil from 'containers/booking-management/booking-util'

class BookingDetails extends React.Component {
  constructor() {
    super();
    this.state = {
      loading: false,
      bookDetailLoading: false,
      pagination: {
        total: 0
      },
      page: 0,
      pageSize: 10,
      travelOrders: [],
      currencyCode: '',
      columns: [
        {
          title: messages('booking-management.key58'/*最后编辑日期*/),
          dataIndex: 'lastModifiedDate',
          render: value => moment(value).format('YYYY-MM-DD')
        },
        {
          title: messages('booking-management.key59'/*航班日期*/),
          dataIndex: 'travelDate',
          render: value => moment(value).format('YYYY-MM-DD')
        },
        {title: messages('booking-management.key60'/*乘机人*/), dataIndex: 'name'},
        {title: messages('booking-management.key61'/*出发机场*/), dataIndex: 'fromAirport'},
        {title: messages('booking-management.key62'/*到达机场*/), dataIndex: 'toAirport'},
        {title: messages('booking-management.key63'/*航班号*/), dataIndex: 'travelNo'},
        {
          title: messages('booking-management.key64'/*最终金额*/),
          dataIndex: 'finalPrice',
          render: value => this.state.currencyCode + this.filterMoney(value, 2, true)
        },
        {
          title: messages('booking-management.key65'/*机票状态*/),
          dataIndex: 'status',
          width: '18%',
          render: (e, record) => {
            let status = constants.getTextByValue(record.status, 'ticketStatus');
            let charW = record.confirmStatus !== 1000 ? "，" : "";
            let confirm = constants.getTextByValue(record.confirmStatus, 'ticketConfirmStatus');
            let title = status + charW + confirm;
            return (
              <Tooltip
                placement="topLeft"
                title={title}
                arrowPointAtCenter
              >
                <span>{title}</span>
              </Tooltip>
            )
          }
        },
        {
          title: messages("common.operation"),
          key: 'operation',
          width: '20%',
          render: (e, record) => {
            let isDisable = record.confirmStatus === 1001 ||
              (record.confirmStatus === 1002 && record.status !== 1010) ||
              record.status === 1004 ||
              record.status === 1005 ||
              record.status === 1008 ||
              record.status === 1009 ||
              record.status === 1011 ||
              record.status === 1012;
            let editIsDisabled = record.status === 1008 || record.status === 1011 || record.status === 1012;
            let deleteTip = `${messages('booking-management.key66'/*删除后*/)}，${messages('booking-management.key28'/*乘机人*/)}${record.name}${messages('booking-management.key67'/*将不能在APP中看到此条航班信息，是否确认删除？*/)}`
            return (
              <span>
                <a
                  className={editIsDisabled ? "disabled" : ''}
                  onClick={(e) => this.handleEdit(e, record)}
                >
                  {messages("common.detail")}
                </a>
                <Divider type="vertical"/>
                <a
                  className={record.confirmStatus === 1001 ? "disabled" : ''}
                  onClick={(e) => this.handleCopyEdit(e, record)}
                >
                  {messages("common.edit.copy")}
                </a>
                <Divider type="vertical"/>
                <Popconfirm
                  onConfirm={() => this.handleDelete(e, record)}
                  title={deleteTip}
                >
                   <a
                     className={isDisable ? "disabled" : ''}
                     disabled={isDisable}
                     onClick={(e) => {
                       e.preventDefault();
                       e.stopPropagation();
                     }}
                   >
                     {messages("common.delete")}
                   </a>
                </Popconfirm>
              </span>
            )
          }
        }   //操作
      ],
      bookingDetailList: [
        // //票价审核状态
        // { type: 'text', id: 'status', label: messages("bookingManagement.bookingDetails.ticketPriceStatus")},
        // //最后更新日期
        // { type: 'date', id: 'lastModifiedDate', label: messages("bookingManagement.bookingDetails.lastModifiedDate")},
        //申请单号
        {type: 'text', id: 'businessCode', label: messages('booking-management.key6'/*申请单号*/)},
        //申请人
        {type: 'text', id: 'submittedBy', label: messages('booking-management.key68'/*申请人*/)},
        //提交日期
        {type: 'date', id: 'createdDate', label: messages('booking-management.key69'/*提交日期*/)}
      ],
      bookingDetailData: {
        status: "",
        lastModifiedDate: "",
        businessCode: "",
        submittedBy: "",
        createdDate: ""
      },
      info: {},
      applicant: null,
      travelOperationRecords: [],
      participantName: "",
      travelBookerApplication: {},
      custFormValues: [],
      viewData: { //拿来装custFormValues解析之后的数据
        outParticipantName: [],
        innerParticipant: [],
        outParticipantNum: 0,
        attachments: [],
        baseCurrency: null,
        totalBudget: 0,
        hasBudgetDetail: false,
        expenseBudgetList: [],
        corporationOID: null,
        hasApportion: null
      },
      functionProfile: null,
      showSlideFrame: false,
      content: [],//最新一条travelOperationRecords记录详情内容的DOM结构，依据custFormValues解析后的数据build
      bookingParams: {
        isNew: true,
        isRefund: false,
        isCopy: false,
        travelOrder: {}
      },
      ApplicantVisible: false,
      PassengerVisible: false,
      launchPriceVisible: false,
      checkedList: [],
      indeterminate: false,
      checkAll: false,
      options: [],
      optionValues: [],
      defaultDisplay: {display: "block"},
      // wjk add new version booking
      orderTicketData: {},// 订票信息
      isOpenBookingPlatform: false,// 是否开启了订票平台
      isShowFormInfo: true, // 是否显示申请单信息，在关联了申请单情况下默认显示申请单信息
    };
    this.bookingCommissioner = menuRoute.getRouteItem('booking-commissioner', 'key');
    this.lock = false;// 是否在发起请求
  }

  componentWillMount() {
    bookingManagerService.getFuntionProfile().then((response) => {
      this.setState({functionProfile: response});
    });
    bookingManagerService.getMyCompanyConfiguration().then((response) => { //获取本位币代码
      this.setState({
        viewData: {baseCurrency: response.data.currencyCode},
        currencyCode: response.data.currencyCode
      });
    });
    this.getBookingDetailV2();
  }

  //***************** wjk add method start*****************

  /**
   * 获取订票信息详情。必须先设置当前用户是否是开启了订票平台才可进行请求。
   */
  getBookingDetailV2 = () => {
    const {params} = this.props;
    if (params.isNew === 'true') {
      this.setState({isOpenBookingPlatform: true})
    }
    this.getBookingDetails();
  }

  /**
   * 监听是否显示申请单信息
   */
  onShowFormInfo = () => {
    const {isShowFormInfo} = this.state;
    this.setState({isShowFormInfo: !isShowFormInfo});
  }


//***************** wjk add method end*****************

  getBookingDetails = () => {
    const {params} = this.props;
    const applicationOID = params.applicationOID != 'null' ? params.applicationOID : null;
    const travelOperationRecordOIDs = params.recordOID;
    const options = [];
    const optionValues = [];
    let bookingDetailData = {
      status: "",
      lastModifiedDate: "",
      businessCode: "",
      submittedBy: "",
      createdDate: ""
    };
    let paramsOption = {
      applicationOID,
      travelOperationRecordOIDs,
      oldFunction: !params.isNew,
    };
    this.setState({loading: true});
    bookingManagerService.getBookingDetail(paramsOption).then((response) => {
      bookingDetailData.status = response.data.travelOperationRecords[0].status;//最新状态
      bookingDetailData.lastModifiedDate = response.data.travelOperationRecords[0].lastModifiedDate;
      response.data.travelOrders.map((item) => {
        item.key = item.travelOrderOID;
      });
      response.data.applicationParticipants.map((item) => {
        options.push({
          label: item.fullName, value: item.participantOID
        });
        optionValues.push(item.participantOID);
      });
      if (applicationOID) {
        bookingDetailData.businessCode = response.data.businessCode;// 无申请单时可为空
        bookingDetailData.createdDate = moment(response.data.createdDate).format('YYYY-MM-DD');// 无申请单时可为空
        let applicant = {
          departmentOID: response.data.departmentOID // 无申请单时可为空
        }
        this.setState({
          custFormValues: response.data.custFormValues || [],// 未关联申请单可以为空
          participantName: this.getParticipant(response.data.applicationParticipants),// 无申请单时可为空
          applicant: applicant
        })
        const submittedBy = [response.data.submittedBy];// 申请人 无申请单时也不可为空
        bookingManagerService.getApplicantName(submittedBy).then((response) => {
          bookingDetailData.submittedBy = response.data[0].fullName;
          this.setState({
            bookingDetailData: bookingDetailData,
            loading: false
          });
        });
        this.processCustomValues(response.data.custFormValues);
      }
      // 要展示申请人，但是申请人不在订票信息里。
      response.data.travelOperationRecords[0].applicantName = response.data.travelBookerApplication.applicantName;
      this.setState({
        loading: false,
        orderTicketData: Object.assign({},
          response.data.travelOperationRecords[0],
          {
            applicantPhone: response.data.travelBookerApplication.applicantPhone
          }),
        info: response.data,
        travelOrders: response.data.travelOrders,
        travelOperationRecords: response.data.travelOperationRecords,
        travelBookerApplication: response.data.travelBookerApplication,
        options: options,
        optionValues: optionValues,
      },this.handleIsHandled);
    })
  };

  //处理乘机人数组拿到字符串
  getParticipant = (value) => {
    let participantName = [];
    value.map((item) => {
      participantName.push(item.fullName);
    });
    return participantName.join("、");
  };


  processCustomValues = (customValues = []) => {
    const {viewData} = this.state;
    let customValuesUpdate = customValues;
    customValuesUpdate.map((item) => {
      switch (item.messageKey) {
        case constants.MESSAGE_KEY.externalParticipantName:
        case constants.MESSAGE_KEY.outParticipantName: {
          //外部参与人姓名
          try {
            if (item.value) {
              let personNames = [];
              JSON.parse(item.value).map((person) => {
                personNames.push(`${person.name}-${person.certificateNo}`);
              });
              viewData.outParticipantName = personNames.join('，');
            }
          } catch (error) {
          }
          break;
        }
        case constants.MESSAGE_KEY.participant : {
          //参与人处理
          if (item.value) {
            let personNames = [];
            JSON.parse(item.value).map((person) => {
              person.participantOID = person.userOID;
              personNames.push(person.fullName);
            });
            viewData.innerParticipant = personNames.join('，');
          }
          break;
        }
        case constants.MESSAGE_KEY.outParticipantNum : {
          //外部参与人员的处理
          if (item.value) {
            //如果外部参与人员的fieldtype配成了text要进行类型强转
            if (!isNaN(parseInt(item.value))) {
              viewData.outParticipantNum = parseInt(item.value);
            }
          }
          break;
        }
      }
    });
    this.setState({viewData});
  };
  //翻页
  onChangePager = (page) => {
    if (page - 1 !== this.state.page)
      this.setState({page: page - 1,}, this.getList);
  };

  //编辑
  handleEdit = (e, record) => {
    if (record.status === 1008 || record.status === 1011 || record.status === 1012) {
      return false;
    } else {
      let isRefund = (record.status === 1002);
      this.setState({
        showSlideFrame: true,
        bookingParams: {
          isOldFunc: !this.state.isOpenBookingPlatform,
          isNew: false,
          isRefund: isRefund,
          priceAuditor: this.state.travelBookerApplication.priceAuditor,
          readonly: true,
          isCopy: false,
          currencyCode: this.state.currencyCode,
          travelOrder: record
        }
      });
    }

  };

  //新增员工订票记录
  addEmployeeRecord = () => {
    const {optionValues, orderTicketData, isOpenBookingPlatform, currencyCode, travelBookerApplication} = this.state;
    const {params} = this.props;
    let oid = params.applicationOID;
    this.setState({
      showSlideFrame: true,
      bookingParams: {
        isOldFunc: !isOpenBookingPlatform,
        isNew: true,
        isRefund: false,
        currencyCode: currencyCode,
        priceAuditor: travelBookerApplication.priceAuditor,
        readonly: false,
        isCopy: false,
        travelOrder: {
          "type": 1001, //1001员工,1002外部参与人
          "applicationOID": oid != 'null' ? oid : null,
          "applicationParticipants": {userOIDs: optionValues.join(",")},
          travelOperationRecordOID: orderTicketData.travelOperationRecordOID,
          travelBookerApplicationId: travelBookerApplication.id, // 后端(曾翔)说取这个值
        }
      }
    });
  };

  //复制并编辑
  handleCopyEdit = (e, record) => {
    const {optionValues} = this.state;
    if (record.confirmStatus === 1001) {
      return false;
    } else {
      let isRefund = (record.status === 1002);
      this.setState({
        showSlideFrame: true,
        bookingParams: {
          isOldFunc: !this.state.isOpenBookingPlatform,
          isNew: false,
          isRefund: isRefund,
          priceAuditor: this.state.travelBookerApplication.priceAuditor,
          readonly: false,
          isCopy: true,
          currencyCode: this.state.currencyCode,
          travelOrder: {
            // ...record,
            ...BookingUtil.copyAttribute(record),
            applicationParticipants: {
              userOIDs: optionValues.join(",")
            }
          }
        }
      });
    }
  };

  //确认删除
  handleDelete = (e, record) => {
    if (record.confirmStatus === 1001 ||
      (record.confirmStatus === 1002 &&
        record.status !== 1010) ||
      record.status === 1005 ||
      record.status === 1008 ||
      record.status === 1009 ||
      record.status === 1011 ||
      record.status === 1012) {
      return false;
    } else {
      bookingManagerService.deleteTravelOrder(record.travelOrderOID).then(() => {
        message.success(messages('common.operate.success'));
        this.getBookingDetails();
      }).catch(e => {
        message.error(e.response.data.message);
      });
      // e.stopPropagation();
    }
  };

  //通知申请人确认机票信息
  handleNotifyApplicant = () => {
    if (!this.lock) {
      this.lock = true;
      bookingManagerService.notifyApplicant(this.props.params.applicationOID).then(() => {
        message.success(messages('common.operate.success'));
        this.getBookingDetails();
        this.lock = false;
        this.setState({ApplicantVisible: false});
      }).catch(e => {
        this.lock = false;
        message.error(e.response.data.message);
        this.setState({PassengerVisible: false});
      });
    }
  };

  //发起价格审核
  launchPriceApproval = () => {
    bookingManagerService.launchPriceApproval(this.props.params.applicationOID).then(() => {
      message.success(messages('common.operate.success'));
      this.getBookingDetails();
      this.setState({launchPriceVisible: false});
    }).catch(e => {
      message.error(e.response.data.message);
      this.setState({PassengerVisible: false});
    });

  };

  //通知乘机人机票信息
  handleNotifyPassenger = () => {
    if(this.lock){
      return ;
    }
    if (this.state.checkedList.length) {
      const {isOpenBookingPlatform, travelBookerApplication} = this.state;
      const {params} = this.props;
      let paramsOption = {
        applicationOID: params.applicationOID,
        travelBookerApplicationId: travelBookerApplication.id, // 后端(曾翔)说取这个值,
        oldFunction: !isOpenBookingPlatform,
      }
      this.lock = true;
      bookingManagerService.notifyPassenger(paramsOption, this.state.checkedList).then(() => {
        message.success(messages('common.operate.success'));
        this.getBookingDetails();
        this.lock = false;
      }).catch(e => {
        this.lock = false;
        message.error(e.response.data.message);
        this.setState({PassengerVisible: false});
      });
      this.setState({PassengerVisible: false});
    } else {
      message.error(messages('booking-management.key70'/*请选择乘机人*/));
    }

  };

  //新增外部人员订票记录
  addOuterRecord = () => {
    const {currencyCode, travelBookerApplication} = this.state;
    const {params} = this.props;
    this.setState({
      showSlideFrame: true,
      bookingParams: {
        isNew: true,
        isRefund: false,
        currencyCode: currencyCode,
        priceAuditor: travelBookerApplication.priceAuditor,
        readonly: false,
        isCopy: false,
        travelOrder: {
          "type": 1002, //1001员工,1002外部参与人
          "applicationOID": params.applicationOID
        }
      }
    });
  };

  closeSlide = () => {
    this.refs.form.form.onCancel();
  };

  //关闭侧拉框后刷新列表
  handleCloseNewSlide = (params) => {
    this.setState({
      showSlideFrame: false,
      isNew: false
    }, () => {
      if (params) {
        this.getBookingDetails();
      }
    })
  };

  //关闭模态框通用方法
  handleCancel = (type) => {
    if (type === "ApplicantVisible") {
      this.setState({ApplicantVisible: false});
    }
    if (type === "PassengerVisible") {
      this.setState({PassengerVisible: false});
    }
    if (type === "launchPriceVisible") {
      this.setState({launchPriceVisible: false});
    }
  };

  //打开模态框通用方法
  openModal = (type) => {
    if (type === "ApplicantVisible") {
      this.setState({ApplicantVisible: true});
    }
    if (type === "PassengerVisible") {
      this.setState({PassengerVisible: true});
    }
    if (type === "launchPriceVisible") {
      this.setState({launchPriceVisible: true});
    }
  };

  onChangeCheckBox = (checkedList) => {
    const {options} = this.state;
    this.setState({
      checkedList,
      indeterminate: !!checkedList.length && (checkedList.length < options.length),
      checkAll: checkedList.length === options.length,
    });
  };

  onCheckAllChange = (e) => {
    const {optionValues} = this.state;
    this.setState({
      checkedList: e.target.checked ? optionValues : [],
      indeterminate: false,
      checkAll: e.target.checked,
    });
  };


  handleIsHandled = (index = 0) => {
    const {travelOperationRecords, defaultDisplay} = this.state;
    this.setState({
      defaultDisplay: defaultDisplay.display === "block" ? {display: "none"} : {display: "block"}
    }, () => {
      if (!index && travelOperationRecords.length && !travelOperationRecords[index].hasHandled) {
        bookingManagerService.handOperation(travelOperationRecords[index].travelOperationRecordOID).then(() => {
          travelOperationRecords[index].hasHandled = true;
          this.setState({
            travelOperationRecords: travelOperationRecords
          })
        });
      }
    });
  };

  //返回申请单详情
  renderBookingDetails() {
    const {travelOperationRecords, loading} = this.state;
    const collapseStyle = {
      background: '#ffffff',
      borderRadius: 4,
      border: 3,
    };
    let children = [];
    travelOperationRecords.map((item, index) => {
      children.push(this.renderContent(item));
    });
    return (
      <Spin spinning={loading}>
          {children}
      </Spin>
    );
  }

  //返回申请单详情travelOperationRecords条目展开部分详情
  renderContent = (item) => {
    if (true || item.type === 1001) {// wjk  add true 按照申请单配置显示属性值 19.07.16 10:13
      const {custFormValues, info, applicant} = this.state;
      return (
        <Row>
          {customField.renderFields(custFormValues, info, applicant)}
        </Row>
      );
    }
  };

  render() {
    const {loading, pagination, columns, travelOrders, showSlideFrame, bookingParams} = this.state;
    const {ApplicantVisible, PassengerVisible, launchPriceVisible, bookingDetailData} = this.state;
    const {travelBookerApplication, options, orderTicketData, isOpenBookingPlatform, isShowFormInfo} = this.state;
    const {applicationOID} = this.props.params;
    return (
      <div className="booking-details background-transparent">
        <Card title={messages('booking-management.key21')/*订票信息*/} bordered={false} className="booking-content">
          <TicketInfo info={orderTicketData} onFormInfo={this.onShowFormInfo}/>
        </Card>
        <div style={{marginTop: 20}}/>
        {isShowFormInfo && applicationOID && (
          <Card title={messages('booking-management.key82'/*申请单详情*/)} bordered={false} className="booking-content">
            {this.renderBookingDetails()}
          </Card>
        )
        }
        <div style={{marginTop: 20}}/>
        <Card bordered={false} className="booking-content">
          <Button
            type="primary" icon="plus-circle-o"
            onClick={() => this.addEmployeeRecord()}
          >
            {messages('booking-management.key83'/*新增员工订票记录*/)}
          </Button>
          {!isOpenBookingPlatform &&
            <Button
              type="primary"
              icon="plus-circle-o"
              onClick={() => this.addOuterRecord()}
            >
              {messages('booking-management.key84'/*新增外部人员订票记录*/)}
            </Button>
          }
          <ResizeTable
            loading={loading}
            pagination={pagination}
            dataSource={travelOrders}
            columns={columns}
            size="middle"
            bordered
          />
        </Card>
        <SlideFrame
          title={bookingParams.isCopy ? messages("common.edit.copy") : messages("common.edit")}
          show={showSlideFrame}
          content={BookingDetailsMaintain}
          onClose={this.closeSlide}
          afterClose={this.handleCloseNewSlide}
          params={bookingParams}
          ref="form"
        />
        <Modal
          title={messages('booking-management.key85'/*通知申请人确认机票信息*/)}
          visible={ApplicantVisible}
          onOk={this.handleNotifyApplicant}
          onCancel={() => this.handleCancel("ApplicantVisible")}
        >
          <p>{`${messages('booking-management.key4'/*申请人*/)}：${bookingDetailData.submittedBy} ${messages('booking-management.key57'/*将在汇联易APP内收到航班信息，请仔细核对信息后确认*/)}`}</p>
        </Modal>
        <Modal
          title={messages('booking-management.key86'/*发起价格审核*/)}
          visible={launchPriceVisible}
          onOk={this.launchPriceApproval}
          onCancel={() => this.handleCancel("launchPriceVisible")}
        >
          <p>{messages('booking-management.key87'/*是否发起价格审核？*/)}</p>
        </Modal>
        <Modal
          title={messages('booking-management.key88'/*通知乘机人机票信息*/)}
          visible={PassengerVisible}
          onOk={this.handleNotifyPassenger}
          onCancel={() => this.handleCancel("PassengerVisible")}
          // okButtonProps={{ disabled: !this.state.checkedList.length}} antd3.8以后才支持
        >
          <div>
            <div style={{borderBottom: '1px solid #E9E9E9'}}>
              <Checkbox
                indeterminate={this.state.indeterminate}
                onChange={this.onCheckAllChange}
                checked={this.state.checkAll}
              >
                {messages("common.selectAll")}
              </Checkbox>
            </div>
            <br/>
            <CheckboxGroup options={options} value={this.state.checkedList} onChange={this.onChangeCheckBox}/>
          </div>
        </Modal>
        <Affix offsetBottom={0} className="bottom-bar">
          {
            !isOpenBookingPlatform && (
              <Button type="primary" onClick={() => this.openModal("ApplicantVisible")}>
                {messages('booking-management.key85'/*通知申请人确认机票信息*/)}
              </Button>
            )
          }
          {/*<Button type="primary" onClick={() => this.openModal("launchPriceVisible")} disabled={!travelBookerApplication.priceAuditor}>*/}
          {/*messages('booking-management.key86')发起价格审核*/}
          {/*</Button>*/}
          <Button type="primary" onClick={() => this.openModal("PassengerVisible")}>
            {messages('booking-management.key88'/*通知乘机人机票信息*/)}
          </Button>
          <Button onClick={() => {
            this.context.router.push(this.bookingCommissioner.url)
          }} icon="rollback" className="back-btn">
            {messages("common.back")/*返回*/}
          </Button>
        </Affix>
      </div>
    )
  }
}

BookingDetails.contextTypes = {
  router: React.PropTypes.object
};

export default BookingDetails;
